package com.yzc35326.typeapp

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import java.io.BufferedReader
import java.io.FileInputStream


class MainActivity : AppCompatActivity() {
    private val TAG = "MainActivity"
    private lateinit var sp: SharedPreferences
    private lateinit var etContent: EditText
    private lateinit var number: EditText
    private lateinit var btnConfirm: Button
    private lateinit var rv: RecyclerView
    private lateinit var etPath: EditText
    private var contentArray = ArrayList<String>()
    private lateinit var adapter: ItemAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        sp = getSharedPreferences("dict_path", Context.MODE_PRIVATE)
        //如果没有授予所有空间的访问权限，就请求用户授权
        //Android6.0版本之上，请求获取所有空间权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                    ),
                    1
                )
            }
        }
        //如果在11及以上版本，请求所有空间的
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager()) {
            val alertDialog = AlertDialog.Builder(this)
                .setMessage("本程序需要您授予对所有空间的访问权限，以便于您可以使用任意位置的自定义码表\n如果取消授权，则只可以使用自带的码表")
                .setPositiveButton("确定") { _, _ ->
                    val intent = Intent()
                    intent.data = Uri.parse("package:com.yzc35326.typeapp")
                    intent.action = Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION
//                    intent.action = Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION
                    startActivity(intent)
                }// /sdcard/2.txt /sdcard/2.txt
                .setNegativeButton("取消") { _, _ ->
                    Toast.makeText(this, "您取消了授权", Toast.LENGTH_SHORT).show()
                }.setCancelable(false)

            alertDialog.show()

        }

//        try {
//            val file = Util.readFile(this, "1")
//            val fileout = openFileOutput("2.txt", Context.MODE_PRIVATE)
//            val bow = BufferedWriter(OutputStreamWriter(fileout, "UTF-8"))
//            var s: String
//            s = file.readLine()
//            while (s.isNotEmpty()) {
//                if (s.split("\t")[0].length == 1)
//                    bow.write("$s\n")
//                s = file.readLine()
//            }
//            bow.close()
//            file.close()
//        } catch (e: Exception) {
//            Log.e(TAG, "onCreate: ", e)
//        } finally {
//
//        }
        this.etPath = findViewById(R.id.et_path)
        this.etContent = findViewById(R.id.et_main_content)
        this.number = findViewById(R.id.et_main_number)
        this.btnConfirm = findViewById(R.id.btn_main_confirm)
        this.rv = findViewById(R.id.rv_main)
        rv.layoutManager = LinearLayoutManager(this)

        btnConfirm.setOnClickListener { _ ->

            val path = this.etPath.text.toString()
//            Log.d(TAG, "存入SP：$path ")
            val oldPath = this.sp.getString("data", "0")
//            Log.d(TAG, "老的路径：$oldPath")
            if (oldPath != path) {
                //如果不同，存入sp中
//                Log.d(TAG, "存入SP：$path ")
                val editor = this.sp.edit()
                editor.putString("dict_path", path)
                editor.apply()
            }
            val readFile: BufferedReader
            try {
                readFile = Util.readFile(this, path)
            }catch (e:Exception){
                Toast.makeText(this,e.message,Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }
            adapter = ItemAdapter(readFile, this, contentArray, path)
            rv.adapter = adapter
            val trim = etContent.text.toString().trim()
            var number: Int = 0
            try {
                number = this.number.text.toString().toInt()
            } catch (e: Exception) {
                Toast.makeText(this,"字数设置有误,请输入整数:\n${e.message}\n $e",Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }

            var count = 0
            var item: String
            var endIndex: Int//endinde不包括在内
            endIndex = count + number
            if (endIndex >= trim.length) {
                endIndex = trim.length
            }
            // count:0   endindex=2 01 你好呀
//            Log.d(TAG, "onCreate: -----------------$count $endIndex")
            item = trim.substring(count, endIndex)

            contentArray.clear()
            while (item.isNotEmpty()) {
                contentArray.add(item)
                count += number
                endIndex = count + number
                if (endIndex >= trim.length) {
                    endIndex = trim.length
                }
//                Log.d(TAG, "onCreate: -----------------$count $endIndex")
                if (count >= trim.length) {
                    break;
                }
                item = trim.substring(count, endIndex)
            }
            if(contentArray.isEmpty()){
                Toast.makeText(this,"您没有输入文字",Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }else{
                adapter.notifyDataSetChanged()
            }

        }
    }

    override fun onResume() {
        super.onResume()
        Log.d(TAG, "onResume: ")
        val path: String = sp.getString("dict_path", "0")!!
        Log.d(TAG, "onResume: ${path}")
        if (path == "0") {//说明没有设置过路径
            this.etPath.setText("")
        } else {
            this.etPath.setText(path)
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            1 -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    val file = FileInputStream("/storage/emulated/0/2.txt")
//                    Log.d(TAG, "onRequestPermissionsResult: ${file.read().toChar()}")
                } else {
                    Toast.makeText(this, "您取消了授权", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
}